<template>
  <div class="fba-boxing-wrap">
    <div class="left-w">
      <h3>发货装箱</h3>
      <div class="flex" style="margin-bottom: 10px">
        <a-input v-model="billNo" placeholder="输入发货单号或扫描发货单条码" allow-clear />
        <a-button style="margin-left: 10px" type="primary" @click="startSearch"><icon-search /></a-button>
      </div>
      <a-alert type="warning" v-if="showResultStatus === 2">抱歉，该发货单状态为{{ tabsMap[fbaDetail.status] }}，无法进行装箱！</a-alert>
      <a-alert type="warning" v-if="showResultStatus === 3">抱歉，该发货单已绑定FBA货件，无法进行装箱！</a-alert>
      <a-alert type="warning" v-if="showResultStatus === 4">抱歉，该发货单明细还未全部锁定库存，无法进行装箱！</a-alert>

      <div class="fba-detail">
        <p class="base-item">
          <span class="label">发货单号：</span>
          <span>{{ fbaDetail.billNo }}</span>
        </p>
        <p class="base-item">
          <span class="label">创建人：</span>
          <span>{{ fbaDetail.createUname }}</span>
        </p>
        <p class="base-item">
          <span class="label">创建时间：</span>
          <span>{{ $setTime(fbaDetail.gmtCreate, 'YYYY/MM/DD HH:mm') }}</span>
        </p>
        <p class="base-item">
          <span class="label">发货仓库：</span>
          <span>{{ fbaDetail.warehouseName }}</span>
        </p>
        <p class="base-item">
          <span class="label">扣减包材库存：</span>
          <span>{{ fbaDetail.needPackage ? '是' : '否' }}</span>
        </p>
        <p class="base-item">
          <span class="label">包材出货仓：</span>
          <span>{{ fbaDetail.packageWarehouseName }}</span>
        </p>
        <div class="base-item">
          <span class="label">附件：</span>
          <ul style="margin-right: 10px" v-if="fbaDetail.attachment">
            <li v-for="(url, i) in fbaDetail.attachment.split(',')" style="margin-bottom: 4px" :key="i">
              <a-tag color="arcoblue" class="cursor" @click="downloadFile(url)">
                <p class="text-limit" style="width: 180px">{{ url }}</p>
                <icon-to-bottom />
              </a-tag>
            </li>
          </ul>
        </div>
        <p class="base-item">
          <span class="label">备注：</span>
          <span>{{ fbaDetail.remark }}</span>
        </p>
      </div>
    </div>
    <div class="right-w">
      <div class="fab-item-w">
        <p style="margin-bottom: 5px">发货单明细</p>
        <a-table class="table-normal-line" :data="fbaDetail.skuDetails" size="mini" :scroll="{ x: '100%', y: 300 }" :summary="true" :bordered="false" :pagination="false">
          <template #columns>
            <a-table-column data-index="img" title="图片" :width="60">
              <template #cell="{ record }">
                <ImgPopover :src="record.productImg">
                  <template #con>
                    <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                  </template>
                </ImgPopover>
              </template>
            </a-table-column>
            <a-table-column title="MSKU/ASIN" :width="120">
              <template #cell="{ record }">
                <TextLimit :rows="1">{{ record.msku }}</TextLimit>
                <TextLimit :rows="1">{{ record.asin }}</TextLimit>
              </template>
            </a-table-column>
            <a-table-column title="FNSKU/SKU" :width="120">
              <template #cell="{ record }">
                <TextLimit :rows="1">{{ record.fnsku }}</TextLimit>
                <ShowSpuDetailBySku :val="record.sku" :showLimit="true" :rows="1" />
              </template>
            </a-table-column>
            <a-table-column data-index="salesmanName" title="销售员" :width="70" />
            <a-table-column data-index="packageName" title="包装" :width="120" />
            <a-table-column data-index="packageSku" title="包装SKU" :width="100" />
            <a-table-column title="包装数" :width="60">
              <template #cell="{ record }">
                <p>{{ record.realNum }}</p>
              </template>
            </a-table-column>
            <a-table-column data-index="realNum" title="发货数" :width="70">
              <template #cell="{ record, rowIndex }">
                <div class="flex-c">
                  <p style="width: 34px">{{ record.realNum }}</p>
                  <a-tooltip content="点击调整发货数量">
                    <i class="icon icon-suozhu highlight cursor" @click="openUpdateNum(rowIndex)"></i>
                  </a-tooltip>
                </div>
              </template>
            </a-table-column>
            <a-table-column data-index="unboxedNum" title="未装箱数" :width="70" />
            <a-table-column :width="130">
              <template #title>
                <div class="flex-c-sb" style="width: 120px">
                  <p>操作</p>
                  <a-button type="text" size="mini" @click="toBoxBatch">一键装箱</a-button>
                </div>
              </template>
              <template #cell="{ record }">
                <div class="flex-c">
                  <a-input-number v-model="record.inboxNum" style="width: 90px" placeholder="" :min="1" :max="record.unboxedNum" />
                  <i class="icon icon-zhuangxiang highlight cursor" @click="toBoxSingle(record)"></i>
                </div>
              </template>
            </a-table-column>
          </template>
          <template #summary-cell="{ column, record }">
            <p v-if="column.dataIndex == 'img'">合计</p>
            <p v-else-if="['realNum', 'unboxedNum'].includes(column.dataIndex)">{{ record[column.dataIndex] }}</p>
          </template>
        </a-table>
      </div>
      <div class="box-item-w">
        <div class="flex-c-sb">
          <ul class="flex-c boxs-list">
            <li v-for="(item, i) in boxList" :key="i" :class="{ active: boxIndex == i }" @click="boxIndex = i">
              <span>箱子{{ i + 1 }}</span>
              <icon-close v-if="boxList.length > 1" style="margin-left: 2px" @click.stop="deleteBox(i)" />
            </li>
            <a-button type="primary" style="margin-left: 30px" size="mini" @click.stop="addBox">加箱</a-button>
          </ul>
          <div>
            <a-button style="margin-right: 20px" @click="savaBoxInfo">保存</a-button>
            <a-button type="primary" style="margin-right: 20px" @click="submitBox" :loading="submitLoading">装箱完成</a-button>
          </div>
        </div>
        <ul class="flex-c boxs-item">
          <li v-for="(item, i) in boxList" :key="i" v-show="boxIndex === i">
            <div class="box-size" style="margin: 10px 0">
              <div class="flex-c">
                <p style="width: 165px"><span style="width: 60px">箱号：</span>B{{ i + 1 }}</p>
                <div class="flex-c">
                  <p><span class="warningColor">*</span>重量：</p>
                  <a-input-number size="small" v-model="item.weight" style="width: 120px" placeholder="" :min="0" />
                  <span>KG</span>
                  <p style="margin-left: 40px">
                    <span v-if="item.weight || item.weight === 0">{{ ((item.weight || 0) * 2.2046).toFixed(2) }}</span>
                    <span v-else>--</span>
                    <span style="margin-left: 4px">磅</span>
                  </p>
                </div>
              </div>
              <div class="flex-c" style="margin-top: 10px">
                <p>箱规：</p>
                <span class="warningColor">*</span>
                <a-input-number size="small" v-model="item.length" style="width: 80px" placeholder="" :min="0" />
                <span>CM</span>
                <span class="warningColor">*</span>
                <a-input-number size="small" v-model="item.width" style="width: 80px" placeholder="" :min="0" />
                <span>CM</span>
                <span class="warningColor">*</span>
                <a-input-number size="small" v-model="item.height" style="width: 80px" placeholder="" :min="0" />
                <span>CM</span>
                <p style="margin-left: 40px">
                  <span v-if="item.length || item.length === 0">{{ ((item.length || 0) * 0.3937).toFixed(2) }}</span>
                  <span v-else>--</span>
                  <span style="margin-left: 4px">in</span>
                </p>
                <p style="margin-left: 20px">
                  <span v-if="item.width || item.width === 0">{{ ((item.width || 0) * 0.3937).toFixed(2) }}</span>
                  <span v-else>--</span>
                  <span style="margin-left: 4px">in</span>
                </p>
                <p style="margin-left: 20px">
                  <span v-if="item.height || item.height === 0">{{ ((item.height || 0) * 0.3937).toFixed(2) }}</span>
                  <span v-else>--</span>
                  <span style="margin-left: 4px">in</span>
                </p>
              </div>
            </div>
            <div class="flex-c" style="margin-bottom: 5px">
              <p>已装箱：{{ item.boxSkus.length }} SKU</p>
              <p style="margin-left: 20px">{{ getSkuNum(item.boxSkus) }} 件</p>
            </div>
            <a-table class="table-normal-line" :data="item.boxSkus" size="mini" :scroll="{ x: '100%', y: '100%' }" :bordered="false" :pagination="false">
              <template #columns>
                <a-table-column data-index="img" title="图片" :width="60">
                  <template #cell="{ record }">
                    <ImgPopover :src="record.productImg">
                      <template #con>
                        <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                      </template>
                    </ImgPopover>
                  </template>
                </a-table-column>
                <a-table-column title="MSKU/ASIN" :width="120">
                  <template #cell="{ record }">
                    <TextLimit :rows="1">{{ record.msku }}</TextLimit>
                    <TextLimit :rows="1">{{ record.asin }}</TextLimit>
                  </template>
                </a-table-column>
                <a-table-column title="FNSKU/SKU" :width="120">
                  <template #cell="{ record }">
                    <TextLimit :rows="1">{{ record.fnsku }}</TextLimit>
                    <ShowSpuDetailBySku :val="record.sku" :showLimit="true" :rows="1" />
                  </template>
                </a-table-column>
                <a-table-column data-index="salesmanName" title="销售员" :width="70" />
                <a-table-column data-index="packageName" title="包装" :width="120" />
                <a-table-column data-index="packageSku" title="包装SKU" :width="100" />
                <a-table-column data-index="inboxNum" title="装箱数" :width="70" />
                <a-table-column title="操作" :width="130">
                  <template #cell="{ rowIndex }">
                    <a-button type="text" size="mini" @click="removeBoxItem(i, rowIndex)">移除</a-button>
                  </template>
                </a-table-column>
              </template>
              <template #summary-cell="{ column, record }">
                <p v-if="column.dataIndex == 'img'">合计</p>
                <p v-else-if="['packNum', 'unboxedNum', 'num'].includes(column.dataIndex)">{{ record[column.dataIndex] }}</p>
              </template>
            </a-table>
          </li>
        </ul>
      </div>
    </div>
  </div>
  <!-- 编辑发货数 -->
  <UpdateFbaNum v-if="showUpdateNum" :fbaDetail="fbaDetail" :currentIndex="currentIndex" :isShow="showUpdateNum" @closed="showUpdateNum = false" />
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { getFbaShipmentInfoByBillNo, updateFbaShipmentByStore, confirmFbaShipmentInBoxByStore } from '@/api/purchase'
  import { useRouter, useRoute } from 'vue-router'
  import useVisitedRouteStore from '@/store/modules/visited-routes'
  import UpdateFbaNum from '@/views/purchase/fbaManagement/components/updateFbaNum.vue'

  onMounted(() => {
    getFbaDetail(window.sessionStorage.getItem('FBABillNo'))
  })

  const tabsMap = {
    DRAFT: '待处理',
    INBOX: '装箱中',
    TO_BE_BIND: '绑定货件',
    TO_BE_SHIPPED: '待发货',
    SHIPPED: '已发货',
    FINISHED: '已入库',
    ERROR: '取消/异常',
  }
  const billNo = ref()
  const showUpdateNum = ref(false)
  const boxIndex = ref(0)
  const showResultStatus = ref(0)
  const fbaDetail = ref<any>({})
  const currentIndex = ref(0)
  const submitLoading = ref(false)
  const route = useRoute()
  const router = useRouter()
  const visitedRouteStore = useVisitedRouteStore()
  const boxList = ref<Array<any>>([
    {
      boxSkus: [],
    },
  ])
  //
  function startSearch() {
    if (!billNo.value) return
    getFbaDetail(billNo.value)
  }
  // 获取FBA详情
  async function getFbaDetail(id: any) {
    if (!id) {
      Message.error('请输入货件单号查询')
      showResultStatus.value = 0
      return
    }
    const res: any = await getFbaShipmentInfoByBillNo({ billNo: id })
    if (!res?.data) {
      showResultStatus.value = 0
      return
    }
    showResultStatus.value = 0
    fbaDetail.value = res?.data || {}
    if (fbaDetail.value.boxDetails?.length) {
      boxList.value = fbaDetail.value.boxDetails.map((el: any) => {
        el.width = Number(el.width)
        el.weight = Number(el.weight)
        el.length = Number(el.length)
        el.height = Number(el.height)
        return el
      })
    }

    window.sessionStorage.setItem('FBABillNo', id)
    setFbaResultStatus()
    getUnboxedNumBatch()
    billNo.value = null
  }
  // 设置当前FBA状态
  function setFbaResultStatus() {
    if (fbaDetail.value.status != 'INBOX') {
      // 未在装箱中状态
      showResultStatus.value = 2
    } else if (fbaDetail.value.shipmentId) {
      // 已绑定FBA货件
      showResultStatus.value = 3
    } else if (!isLockAll()) {
      // 未全部锁定库存
      showResultStatus.value = 4
    } else {
      showResultStatus.value = 1
    }
  }
  //  下载
  function downloadFile(url: string) {
    let _url = url
    if (_url.indexOf('?') > -1) {
      _url += '&response-content-type=application/octet-stream'
    } else {
      _url += '?response-content-type=application/octet-stream'
    }
    let link = document.createElement('a')
    link.href = _url
    link.click()
  }
  //是否全部锁定库存
  function isLockAll() {
    return !fbaDetail.value.skuDetails?.some((el: any) => el.lockStatus != 1)
  }
  // 获取当前箱子sku数量
  function getSkuNum(list: Array<any>) {
    return list.reduce((acc, item: any) => {
      acc += Number(item.inboxNum || 0)
      return acc
    }, 0)
  }
  // 计算未装箱数批量
  function getUnboxedNumBatch() {
    fbaDetail.value.skuDetails.forEach((el: any) => {
      getUnboxedNumSingle(el)
    })
  }
  // 计算未装箱数单个
  function getUnboxedNumSingle(row: any) {
    let inboxNum = 0
    boxList.value.forEach((el: any) => {
      el.boxSkus.forEach((item: any) => {
        if (item.msku == row.msku) {
          inboxNum += item.inboxNum
        }
      })
    })
    row.unboxedNum = row.realNum - inboxNum
  }

  // 删除箱子
  function deleteBox(i: number) {
    boxList.value.splice(i, 1)
    if (boxIndex.value === i) {
      boxIndex.value = 0
    }
    getUnboxedNumBatch()
  }
  // 添加箱子
  function addBox() {
    boxList.value.push({
      boxSkus: [],
    })
  }
  // 编辑发货数
  function openUpdateNum(index: number) {
    currentIndex.value = index
    showUpdateNum.value = true
  }
  // 单个装箱
  function toBoxSingle(row: any) {
    if (!row.inboxNum) return
    let _boxList = boxList.value[boxIndex.value]?.boxSkus || []
    let currentSku = _boxList.find((el: any) => el.msku === row.msku)
    if (!currentSku) {
      _boxList.push(JSON.parse(JSON.stringify(row)))
    } else {
      currentSku.inboxNum += row.inboxNum
    }
    row.inboxNum = null
    getUnboxedNumSingle(row)
  }
  // 一键装箱
  function toBoxBatch() {
    fbaDetail.value.skuDetails.forEach((el: any) => {
      el.inboxNum = el.unboxedNum
      toBoxSingle(el)
    })
  }
  // 移除箱子明细
  function removeBoxItem(parentIndex: number, childIndex: number) {
    boxList.value[parentIndex].boxSkus.splice(childIndex, 1)
    getUnboxedNumBatch()
  }
  // 保存装箱信息
  function getSaveData() {
    let boxDetails = boxList.value.map((el: any, i: number) => {
      return {
        ...el,
        height2: el.height ? (el.height * 0.3937).toFixed(2) : '',
        width2: el.width ? (el.width * 0.3937).toFixed(2) : '',
        length2: el.length ? (el.length * 0.3937).toFixed(2) : '',
        weight2: el.weight ? (el.weight * 2.2046).toFixed(2) : '',
        weightUnit: 'KG',
        weightUnit2: 'lb',
        specsUnit: 'CM',
        specsUnit2: 'in',
        num: 'B' + (i + 1),
        boxNum: getSkuNum(el.boxSkus),
      }
    })
    return {
      id: fbaDetail.value.id,
      boxDetails,
    }
  }
  // 保存装箱信息
  async function savaBoxInfo() {
    if (showResultStatus.value != 1) {
      Message.error('该货件无法装箱')
      return
    }
    let savaData = getSaveData()
    const res = await updateFbaShipmentByStore(savaData)
    if (res) {
      Message.success('保存成功')
    }
  }
  // 完成装箱
  async function submitBox() {
    let flag = false
    fbaDetail.value.skuDetails.forEach((el: any) => {
      if (el.unboxedNum > 0) {
        flag = true
      }
    })
    if (flag) {
      Message.error('请保证所有的明细都已装箱')
      return
    }
    boxList.value.forEach((el: any) => {
      if (!el.weight || !el.length || !el.width || !el.height) {
        flag = true
      }
    })
    if (flag) {
      Message.error('所有箱子的重量和规格都必须填写')
      return
    }
    let savaData = getSaveData()
    const res = await confirmFbaShipmentInBoxByStore(savaData)
    if (res) {
      Message.success('装箱成功')
      removeRoute()
    }
  }
  function removeRoute() {
    router.go(-1)
    visitedRouteStore.removeVisitedRoute(route)
  }
</script>
<style lang="less" scoped>
  .fba-boxing-wrap {
    display: flex;
    .left-w {
      height: calc(100vh - @menuHeight);
      flex-shrink: 0;
      background-color: #fff;
      width: 30%;
      max-width: 450px;
      min-width: 320px;
      margin-right: 5px;
      padding: 20px;
      h3 {
        font-weight: bold;
        font-size: 16px;
        margin-bottom: 5px;
      }
      .fba-detail {
        margin-top: 20px;
        .base-item {
          display: flex;
          margin-bottom: 10px;
          .label {
            width: 100px;
            text-align: right;
            flex-shrink: 0;
            color: #666;
          }
        }
      }
    }
    .right-w {
      height: calc(100vh - @menuHeight);
      background-color: #fff;
      flex: 1;
      padding: 10px;
      overflow: hidden;
      .icon-zhuangxiang {
        font-size: 20px;
        margin-left: 10px;
      }
      .box-item-w {
        margin-top: 10px;
      }
      .boxs-list {
        display: flex;
        flex-wrap: wrap;
        li {
          width: 70px;
          text-align: center;
          line-height: 30px;
          border-bottom: 1px solid transparent;
          margin-right: 5px;
          cursor: pointer;
        }
        li.active {
          border-bottom: 1px solid rgb(var(--primary-6));
          color: rgb(var(--primary-6));
        }
      }
      .box-size {
        background-color: #f8f8f8;
        padding: 10px 20px;
        font-size: 12px;
      }
    }
  }
</style>
